/**
 * FeelScroll
 * -------------
 * Versin 1.01
 * Create time 2017-4-14 10:24:26
 * Author cicime
 */

class FeelSll {

  constructor(cfg = {}) {
    this.cfg = cfg
    this.H = document.documentElement.clientHeight
    this.MT = 0
    this.MB = this.H
    window.addEventListener('scroll', this._init.bind(this), false)
  }

  _scroll() {
    const elements = document.querySelectorAll('[data-feel]')
    const st = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop

    for (let i = 0; i < elements.length; i++) {
      let t = elements[i].offsetTop - st

      if (t < this.MB && t > this.MT - elements[i].clientHeight) {

        elements[i].classList.add('feel-active')
        this.trigger(elements[i], 'active')

      } else {

        elements[i].classList.remove('feel-active')
        this.trigger(elements[i], 'leave')

      }
    }
  }

  trigger(dom, type) {
    let eve = document.createEvent('HTMLEvents')
    eve.initEvent(type, false, false)
    dom.dispatchEvent(eve)
  }

  _init() {
    debounce(this._scroll, 60, this)
  }
}


let _time = null

function debounce(fn, delay = 100, ctx, ...args) {
  if (_time) return;
  fn.apply(ctx, args)
  _time = setTimeout(() => _time = null, delay)
}


if (ENV === 'development') {
  console.log(`[${ENV}] satarted!`)

  // 例子
  new FeelSll()

  Array.prototype.forEach.call(document.querySelectorAll('[data-feel]'), el => {
    el.addEventListener('active', (e) => {
      e.target.style.background = 'red'
    }, false)

    el.addEventListener('leave', (e) => {
      e.target.style.background = 'blue'
    }, false)
  })
}
